package com.tea.modules.java8.thread.semaphore;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 尝试获取许可的信号量控制
 *
 * @author jaymin
 * @since 2022/3/7 0:49
 */
@Slf4j
public class TrySemaphoreDemo {

    public static void main(String[] args) throws InterruptedException {
        int state = 2;
        final Semaphore semaphore = new Semaphore(3);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 20; i++) {
            executorService.execute(() -> {
                // 能做就做，不做就丢弃
                if (semaphore.tryAcquire()) {
                    doSomeThing();
                    semaphore.release();
                }
            });
        }
        executorService.shutdown();

    }

    private static void doSomeThing() {
        log.info("record");
    }
}
